import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import '../../app_views.dart';

/// 万年历页面视图 - Calendar page view
/// 
/// 基于产品需求文档设计，提供完整的万年历功能
/// Based on product requirements document, providing complete calendar functionality
class CalendarView extends GetView<CalendarLogic> {
  const CalendarView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF1A1B3A), // 深蓝紫色 - Deep blue purple
              Color(0xFF2D1B69), // 紫色 - Purple
              Color(0xFF0F0C29), // 深色 - Dark
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部标题栏 - Top title bar
              _buildTopBar(),
              
              // 主要内容区域 - Main content area
              Expanded(
                child: Obx(() {
                  if (controller.state.value.isLoading && controller.state.value.calendarData.isEmpty) {
                    return const Center(
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    );
                  }
                  
                  if (controller.state.value.errorMessage?.isNotEmpty == true) {
                    return _buildErrorView();
                  }
                  
                  return _buildCalendarContent();
                }),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部标题栏 - Build top title bar
  Widget _buildTopBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          // 返回按钮 - Back button
          IconButton(
            onPressed: () => Get.back(),
            icon: const Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
              size: 24,
            ),
          ),
          
          // 标题 - Title
          Expanded(
            child: Text(
              '万年历',
              style: GoogleFonts.notoSansSc(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
              textAlign: TextAlign.center,
            ),
          ),
          
          // 今天按钮 - Today button
          TextButton(
            onPressed: controller.goToToday,
            child: Text(
              '今天',
              style: GoogleFonts.notoSansSc(
                fontSize: 16,
                color: const Color(0xFFFFD700), // 金色 - Gold
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建日历内容 - Build calendar content
  Widget _buildCalendarContent() {
    return SingleChildScrollView(
      child: Column(
        children: [
          // 月份导航 - Month navigation
          _buildMonthNavigation(),
          
          // 日历网格 - Calendar grid
          _buildCalendarGrid(),
          
          // 选中日期详情 - Selected date details
          _buildSelectedDateDetails(),
        ],
      ),
    );
  }

  /// 构建月份导航 - Build month navigation
  Widget _buildMonthNavigation() {
    return Obx(() => Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: GradientCard.transparent(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 上一月按钮 - Previous month button
            IconButton(
              onPressed: controller.previousMonth,
              icon: const Icon(
                Icons.chevron_left,
                color: Colors.white,
                size: 28,
              ),
            ),
            
            // 月份标题 - Month title
            Text(
              '${controller.state.value.currentMonth.year}年${controller.state.value.currentMonth.month}月',
              style: GoogleFonts.notoSansSc(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            
            // 下一月按钮 - Next month button
            IconButton(
              onPressed: controller.nextMonth,
              icon: const Icon(
                Icons.chevron_right,
                color: Colors.white,
                size: 28,
              ),
            ),
          ],
        ),
      ),
    ));
  }

  /// 构建日历网格 - Build calendar grid
  Widget _buildCalendarGrid() {
    return Obx(() {
      final dates = controller.getMonthDates(controller.state.value.currentMonth);
      
      return Container(
        margin: const EdgeInsets.symmetric(horizontal: 16),
        child: GradientCard.transparent(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              // 星期标题 - Weekday headers
              _buildWeekdayHeaders(),
              
              const SizedBox(height: 8),
              
              // 日期网格 - Date grid
              GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 7,
                  childAspectRatio: 1.0,
                  crossAxisSpacing: 4,
                  mainAxisSpacing: 4,
                ),
                itemCount: dates.length,
                itemBuilder: (context, index) {
                  final date = dates[index];
                  return _buildDateCell(date);
                },
              ),
            ],
          ),
        ),
      );
    });
  }

  /// 构建星期标题 - Build weekday headers
  Widget _buildWeekdayHeaders() {
    const weekdays = ['一', '二', '三', '四', '五', '六', '日'];
    
    return Row(
      children: weekdays.map((weekday) => Expanded(
        child: Center(
          child: Text(
            weekday,
            style: GoogleFonts.notoSansSc(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: Colors.white70,
            ),
          ),
        ),
      )).toList(),
    );
  }

  /// 构建日期单元格 - Build date cell
  Widget _buildDateCell(DateTime date) {
    return Obx(() {
      final isInCurrentMonth = controller.isInCurrentMonth(date);
      final isToday = controller.isToday(date);
      final isSelected = controller.isSelected(date);
      final dayInfo = controller.getDayInfo(date);
      
      return GestureDetector(
        onTap: () => controller.selectDate(date),
        child: Container(
          decoration: BoxDecoration(
            color: isSelected 
                ? const Color(0xFFFFD700).withOpacity(0.3) // 选中状态 - Selected state
                : isToday 
                    ? const Color(0xFF8B5CF6).withOpacity(0.3) // 今天 - Today
                    : Colors.transparent,
            borderRadius: BorderRadius.circular(8),
            border: isToday 
                ? Border.all(color: const Color(0xFF8B5CF6), width: 2)
                : null,
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 公历日期 - Solar date
              Text(
                '${date.day}',
                style: GoogleFonts.notoSansSc(
                  fontSize: 16,
                  fontWeight: isToday ? FontWeight.bold : FontWeight.normal,
                  color: isInCurrentMonth 
                      ? Colors.white 
                      : Colors.white38,
                ),
              ),
              
              // 农历日期或节日 - Lunar date or festival
              if (dayInfo != null) ...[
                const SizedBox(height: 2),
                Text(
                  dayInfo.hasFestivals 
                      ? dayInfo.allFestivals.first
                      : dayInfo.hasSolarTerm 
                          ? dayInfo.solarTerm!
                          : dayInfo.lunarDateText,
                  style: GoogleFonts.notoSansSc(
                    fontSize: 10,
                    color: dayInfo.hasFestivals || dayInfo.hasSolarTerm
                        ? const Color(0xFFFFD700) // 节日/节气用金色 - Festivals/solar terms in gold
                        : isInCurrentMonth 
                            ? Colors.white70 
                            : Colors.white24,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ],
          ),
        ),
      );
    });
  }

  /// 构建选中日期详情 - Build selected date details
  Widget _buildSelectedDateDetails() {
    return Obx(() {
      if (controller.state.value.selectedDayInfo == null) {
        return const SizedBox.shrink();
      }
      
      final dayInfo = controller.state.value.selectedDayInfo!;
      
      return AnimationLimiter(
        child: Container(
          margin: const EdgeInsets.all(16),
          child: Column(
            children: AnimationConfiguration.toStaggeredList(
              duration: const Duration(milliseconds: 375),
              childAnimationBuilder: (widget) => SlideAnimation(
                horizontalOffset: 50.0,
                child: FadeInAnimation(child: widget),
              ),
              children: [
                // 日期标题卡片 - Date title card
                _buildDateTitleCard(dayInfo),
                
                const SizedBox(height: 12),
                
                // 基本信息卡片 - Basic info card
                _buildBasicInfoCard(dayInfo),
                
                const SizedBox(height: 12),
                
                // 宜忌信息卡片 - Suitable and avoid info card
                _buildSuitableAvoidCard(dayInfo),
                
                const SizedBox(height: 12),
                
                // 吉凶神煞卡片 - Auspicious and inauspicious gods card
                _buildGodsCard(dayInfo),
              ],
            ),
          ),
        ),
      );
    });
  }

  /// 构建日期标题卡片 - Build date title card
  Widget _buildDateTitleCard(dynamic dayInfo) {
    return GradientCard.purple(
      padding: const EdgeInsets.all(20),
      child: Column(
        children: [
          Text(
            dayInfo.fullDateText,
            style: GoogleFonts.notoSansSc(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            dayInfo.lunarDateText,
            style: GoogleFonts.notoSansSc(
              fontSize: 16,
              color: Colors.white70,
            ),
          ),
          if (dayInfo.hasSolarTerm) ...[
            const SizedBox(height: 4),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
              decoration: BoxDecoration(
                color: const Color(0xFFFFD700).withOpacity(0.2),
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: const Color(0xFFFFD700), width: 1),
              ),
              child: Text(
                dayInfo.solarTerm!,
                style: GoogleFonts.notoSansSc(
                  fontSize: 12,
                  color: const Color(0xFFFFD700),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建基本信息卡片 - Build basic info card
  Widget _buildBasicInfoCard(dynamic dayInfo) {
    return GradientCard.blue(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '基本信息',
            style: GoogleFonts.notoSansSc(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          const SizedBox(height: 12),
          _buildInfoRow('星座', dayInfo.constellation),
          _buildInfoRow('生肖', dayInfo.chineseZodiac),
          _buildInfoRow('干支', dayInfo.ganZhi),
          _buildInfoRow('五行', dayInfo.fiveElements),
          _buildInfoRow('纳音', dayInfo.nayin),
          _buildInfoRow('冲煞', '${dayInfo.chong} ${dayInfo.sha}'),
        ],
      ),
    );
  }

  /// 构建宜忌信息卡片 - Build suitable and avoid info card
  Widget _buildSuitableAvoidCard(dynamic dayInfo) {
    return GradientCard.gold(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '宜忌信息',
            style: GoogleFonts.notoSansSc(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          const SizedBox(height: 12),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '宜',
                      style: GoogleFonts.notoSansSc(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: const Color(0xFF4ADE80), // 绿色 - Green
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      dayInfo.suitableText,
                      style: GoogleFonts.notoSansSc(
                        fontSize: 12,
                        color: Colors.white70,
                        height: 1.4,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '忌',
                      style: GoogleFonts.notoSansSc(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: const Color(0xFFF87171), // 红色 - Red
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      dayInfo.avoidText,
                      style: GoogleFonts.notoSansSc(
                        fontSize: 12,
                        color: Colors.white70,
                        height: 1.4,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建吉凶神煞卡片 - Build gods card
  Widget _buildGodsCard(dynamic dayInfo) {
    return GradientCard.transparent(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '神煞信息',
            style: GoogleFonts.notoSansSc(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          const SizedBox(height: 12),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '吉神',
                      style: GoogleFonts.notoSansSc(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: const Color(0xFFFFD700), // 金色 - Gold
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      dayInfo.jishenText,
                      style: GoogleFonts.notoSansSc(
                        fontSize: 12,
                        color: Colors.white70,
                        height: 1.4,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '凶神',
                      style: GoogleFonts.notoSansSc(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: const Color(0xFF8B5CF6), // 紫色 - Purple
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      dayInfo.xiongshenText,
                      style: GoogleFonts.notoSansSc(
                        fontSize: 12,
                        color: Colors.white70,
                        height: 1.4,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建信息行 - Build info row
  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        children: [
          SizedBox(
            width: 60,
            child: Text(
              label,
              style: GoogleFonts.notoSansSc(
                fontSize: 12,
                color: Colors.white70,
              ),
            ),
          ),
          Text(
            value,
            style: GoogleFonts.notoSansSc(
              fontSize: 12,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建错误视图 - Build error view
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.white54,
          ),
          const SizedBox(height: 16),
          Text(
            controller.state.value.errorMessage ?? '未知错误',
            style: GoogleFonts.notoSansSc(
              fontSize: 16,
              color: Colors.white70,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: controller.refresh,
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF8B5CF6),
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(24),
              ),
            ),
            child: Text(
              '重试',
              style: GoogleFonts.notoSansSc(
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }
}